import email, csv, re
from datetime import datetime
import model

import logging
logging.basicConfig(level=logging.DEBUG)


def readEmail(s):
    '''Czyta wiadomosci email ze string'a'''
    msg = email.message_from_string(s)

    date = msg['Date']
    date = re.match('(.*) [^ ]*$', date).group(1)
    date = datetime.strptime(date, '%a, %d %b %Y %H:%M:%S')
    sub = msg['subject']
    sub = email.Header.decode_header(sub)[0][0]
    pat = re.compile('za ([^ ]+) ([0-9]{4})$')
    q = pat.search(sub)
    if q is not None:
        sub = unicode(q.group(2) + ' ' + q.group(1), 'cp1250')
    else:
        sub = '?'

    m = model.Message()
    m.msg = sub
    m.date = date
    for part in msg.walk():
        if part.is_multipart():
            continue
#        if part.get_content_maintype() == 'text':
#            continue
        try:
            att_name = part.get_filename(None)
            if not att_name.lower().endswith(".csv"):
                continue
        except:
            continue
        pl = part.get_payload(decode=True)
        lines = pl.splitlines()
        account = parseLines(lines)
        m.accounts.append(account)

    return m

def parseLines(lines, append=True):
    '''Czyta plik csv'''

    x = {"rodzaj_rachunku":"", "waluta":"", "numer_rachunku":"", "nr_rachunku":""}
    reader = csv.reader(lines, delimiter=';', quotechar='"')
    values = []
    keys = []
    account = model.Account()
    for row in reader:
        if len(row) < 1:
            keys = []
            continue

        if row[0].startswith("#"):
            keys = map(cleanColumn, row)
            if keys[ - 1].strip() == '':
                keys = keys[: - 1]
        else:
            values = row

        if len(keys) > 4 and len(values) > 4:
            k = keys
            values = map(encodeValues, values)
            if values[ - 1].strip() == '':
                values = values[: - 1]
            values[ - 1] = toFloat(values[ - 1])
            values[ - 2] = toFloat(values[ - 2])
            values[0] = toDate(values[0])
            values[1] = toDate(values[1])
            t = model.Transaction()
            t.keys = keys
            t.values = values
            if append:
                account.transactions.append(t)
            else:
                account.transactions.insert(0,t)

        if len(keys) > 0 and len(values) > 0 and keys[0] in x.keys():
            x[keys[0]] = values[0].replace(" ", "")

    x["nr_rachunku"] = x["numer_rachunku"] + x["nr_rachunku"]
    x.pop("numer_rachunku")
    account.keys = map(cleanColumn, x)
    account.values = map(encodeValues, x.values())
    return account

def cleanColumn(s):
    return s.replace(" ", "_").replace("\xea", "e").lstrip("#").lower()

def encodeValues(s):
    return s.decode('cp1250')

def toDate(da):
    try:
        s = datetime.strptime(da, "%d-%m-%Y")
    except ValueError:
        s = datetime.strptime(da, "%Y-%m-%d")
    return s.date()

def toFloat(x):
    q = x.replace(" ", "").replace(",", ".")
    f = float(q)
    return f

